//
//  UIButton+YHWebImage.m
//  YHCategory
//
//  Created by 98du on 2021/11/29.
//

#import "UIButton+YHWebImage.h"
#import "UIImage+YHStyle.h"
#import "YHConstant+Null.h"
#import "NSString+YHWebImage.h"
#import <SDWebImage/UIButton+WebCache.h>

@implementation UIButton (YHWebImage)

-(void)yh_setImage:(NSString *)urlString{
    [self yh_setImage:urlString withState:UIControlStateNormal placeholderImage:nil];
}
-(void)yh_setImageOrigin:(NSString *)urlString{
    [self yh_setImage:urlString withState:UIControlStateNormal placeholderImage:[UIImage yh_placeHolder] isOrigin:YES];
}

-(void)yh_setImageHighlight:(NSString *)urlString{
    [self yh_setImage:urlString withState:UIControlStateHighlighted placeholderImage:nil];
}
-(void)yh_setImageSelected:(NSString *)urlString{
    [self yh_setImage:urlString withState:UIControlStateSelected placeholderImage:nil];
}

-(void)yh_setImage:(NSString *)urlString placeholderImage:(nullable UIImage *)placeholderImage{
    [self yh_setImage:urlString withState:UIControlStateNormal placeholderImage:placeholderImage];
}
-(void)yh_setImage:(NSString *)urlString withState:(UIControlState)controlState placeholderImage:(nullable UIImage *)placeholderImage{
    [self yh_setImage:urlString withState:controlState placeholderImage:placeholderImage isOrigin:NO];
}
-(void)yh_setImage:(NSString *)urlString withState:(UIControlState)controlState placeholderImage:(nullable UIImage *)placeholderImage isOrigin:(BOOL)isOrigin{
    if (IsNull(placeholderImage)) {
        placeholderImage = [UIImage yh_placeHolder];
    }
    if(![urlString isKindOfClass:[NSString class]]){
        [self setImage:placeholderImage forState:controlState];
        return;
    }

    NSURL * url = [NSURL URLWithString:urlString];
    if ([url pathComponents].count > 1) {
        NSString * imageURL = urlString.yh_OSSURLPath;
        if(!isOrigin){
            imageURL = [imageURL yh_OSSReszeFit];
        }
        if (placeholderImage) {
            [self sd_setImageWithURL:[NSURL URLWithString:imageURL] forState:controlState placeholderImage:placeholderImage];
        }else{
            [self sd_setImageWithURL:[NSURL URLWithString:imageURL] forState:controlState];
        }
    }else if (IsNull(urlString)) {
        [self setImage:placeholderImage forState:controlState];
    } else{
        UIImage * image = [UIImage imageNamed:urlString];
        if (IsNull(image)) {
            image = placeholderImage;
        }
        [self setImage:image forState:controlState];
    }

}

@end
